//
//  WCNSelectNurseVC.m
//  WCN
//
//  Created by 杨鑫 on 15/7/6.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNSelectNurseVC.h"
//
#import "WCNSelectNurseTCell.h"
#import "WCButton.h"
#import "MJRefresh.h"
//
#import "UINavigationItem+Offset.h"
//
#import "Nurse.h"
//
#import "WCDefaultManager.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCNConstantsCDStore.h"
#import "WCImageManager.h"
//
#import "Macros.h"
#import "Constants.h"

static NSString *cellId = @"WCNSelectNurseTCell";

@interface WCNSelectNurseVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) UITableView *tableView;
@property (weak, nonatomic) WCNSelectNurseTCell *selectedCell;

@property (nonatomic) WCNSelectNurseType selectType;
@property (strong, nonatomic) NSString *url;
@property (strong, nonatomic) NSArray *nurses;
@property (strong, nonatomic) NSMutableArray *selectedNurseIds;

@end

@implementation WCNSelectNurseVC

- (instancetype)init
{
    return [self initWithSelectType:WCNSelectNurseVCMain];
}

- (instancetype)initWithSelectType:(WCNSelectNurseType)type
{
    self = [super init];
    if (self) {
        _selectType = type;
        
        Account *account = [[WCDefaultManager shareMg] account];
        _url = [NSString stringWithFormat:@"nurse/account/by/hospital/%@", account.hospitalId];
        _nurses = [[WCNConstantsCDStore shareStore] getNursesByhospital:account.hospitalId];
        _selectedNurseIds = [NSMutableArray array];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    if (self.selectType == WCNSelectNurseVCMain) {
        self.title = @"选择主护理人";
    } else {
        self.title = @"选择共同护理人";
    }
    
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavHeight)];
    self.tableView = tableView;
    tableView.backgroundColor = kAppBg;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    tableView.rowHeight = 85;
    [tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    if (self.selectType == WCNSelectNurseVCAssist) {
        tableView.allowsMultipleSelection = YES;
    }
    [tableView addLegendHeaderWithRefreshingBlock:^{
        [self refresh];
    }];
    [self.view addSubview:tableView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if ([[WCNetworkAccessManager sharedMg] timeSinceLastUrl:self.url] > kUrlCD && ![self.tableView.header isRefreshing]) {
        [self.tableView.header beginRefreshing];
    }
}

- (void)refresh
{
    [[WCNetworkAccessManager sharedMg] GET:self.url parameters:nil success:^(NSDictionary *result){
        Account *account = [[WCDefaultManager shareMg] account];
        self.nurses = [[WCNConstantsCDStore shareStore] createNurses:result[@"data"] hospital:account.hospitalId];
        [self.tableView reloadData];
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
    }];
}

#pragma mark - Setter

- (void)setSelectdMainNurse:(AccountEntity *)selectdMainNurse
{
    _selectdMainNurse = [selectdMainNurse copy];
}

- (void)setSelectedNurses:(NSMutableArray *)selectedNurses
{
    for (Nurse *nurse in selectedNurses) {
        [self.selectedNurseIds addObject:nurse.stringId];
    }
}

#pragma mark - Actions

- (void)save
{
    NSMutableArray *selectedNurses = [NSMutableArray array];
    for (Nurse *nurse in self.nurses) {
        if ([self.selectedNurseIds indexOfObject:nurse.stringId] != NSNotFound) {
            [selectedNurses addObject:nurse];
        }
    }
    
    self.saveCallback(self.selectdMainNurse, selectedNurses);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    WCNSelectNurseTCell *cell = (WCNSelectNurseTCell *)[tableView cellForRowAtIndexPath:indexPath];
    NurseDetail *nurse = self.nurses[indexPath.row];
    if (self.selectType == WCNSelectNurseVCMain) {
        //判断选择的护理师是否在共同护理师中
        if ([self.selectedNurseIds indexOfObject:nurse.stringId] == NSNotFound) {
            [self.selectedCell selectEffect:NO];
            [self.selectdMainNurse updateWithNurseDetail:nurse];
            self.selectedCell = cell;
            [cell selectEffect:YES];
        } else {
            [[WCPopupLayerManager shareMg] showTextOnly:@"所选主护理人已经在共同护理人列表！" withView:self.view];
            return;
        }
    } else {
//        if (self.selectedNurseIds.count == 8) {
//            [[WCPopupLayerManager shareMg] showTextOnly:@"共同护理人不能超过8位!" withView:self.view];
//            return;
//        }
        
        if ([nurse.stringId isEqualToString:self.selectdMainNurse.stringId]) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"所选共同护理人已经是主护理人！" withView:self.view];
            return;
        }
        
        NSUInteger index = [self.selectedNurseIds indexOfObject:nurse.stringId];
        if (index == NSNotFound) {
            [self.selectedNurseIds addObject:nurse.stringId];
            [cell selectEffect:YES];
        } else {
            [self.selectedNurseIds removeObjectAtIndex:index];
            [cell selectEffect:NO];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCNSelectNurseTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    NurseDetail *nurse = self.nurses[indexPath.row];
    cell.nurseName.text = nurse.name;
    cell.nurseId = nurse.stringId;
    UIImage *image = [[WCImageManager sharedMg] image:nurse.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES];
    if (image) {
        cell.nurseAvatar.image = image;
    } else {
        cell.nurseAvatar.image = [UIImage imageNamed:@"Nurse_default"];
        [[WCImageManager sharedMg] downloadImage:nurse.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
            if ([stringId isEqualToString:cell.nurseId]) {
                cell.nurseAvatar.image = image;
            }
        } failure:nil];
    }
    
    if (self.selectType == WCNSelectNurseVCMain) {
        if ([nurse.stringId isEqualToString:self.selectdMainNurse.stringId]) {
            [cell selectEffect:YES];
            self.selectedCell = cell;
        } else {
            [cell selectEffect:NO];
        }
    } else {
        NSUInteger index = [self.selectedNurseIds indexOfObject:nurse.stringId];
        [cell selectEffect:index==NSNotFound?NO:YES];
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.nurses.count;
}

@end
